package com.fast.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {

	private static Logger logger = LoggerFactory.getLogger("HttpUtil");

	public static void main(String[] args) throws Exception {
		getRemoteImage("http://static.oschina.net/uploads/space/2015/1208/122249_oZs4_1434710.png");
	}
	
	/**
	 * 以post方式提交数据
	 * @param url
	 * @param data，提交的数据
	 * @param dataType ，数据的类型，json或者是默认的表单数据
	 * json时其编码为application/json,为空时：application/x-www-form-urlencoded
	 * @return
	 * 如果要在servlet中获取其数据，需要从inputStream中读取
	 * @throws IOException
	 */
	public static int post( String url , String data , String dataType ) throws IOException{
		URL url1 = new URL(url);
		URLConnection conn = url1.openConnection();
		HttpURLConnection httpConn = (HttpURLConnection) conn;
		httpConn.setRequestMethod("POST");
		httpConn.setRequestProperty("User-Agent",	"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36");
		httpConn.setRequestProperty("Referer", "http://www.baidu.com/");
		httpConn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
		httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
		httpConn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
		httpConn.setDoOutput(true);
		httpConn.setDoInput(true);
		//httpConn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); //x-www-form-urlencoded
		//提交json数据
		if( "json".equals(dataType) ){
			httpConn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
		}else{
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		}
		logger.info("收到的报文：{}" , data);
		OutputStreamWriter out = new OutputStreamWriter(httpConn.getOutputStream());
		out.write(data);
		out.flush();
		
		String encoding = httpConn.getContentEncoding();
		InputStreamReader read = null;
		InputStream is = httpConn.getInputStream();
		if ("gzip".equalsIgnoreCase(encoding)) {
			GZIPInputStream gzip = new GZIPInputStream(is);
			read = new InputStreamReader(gzip, "UTF-8");
		} else {
			read = new InputStreamReader(is, "UTF-8");
		}
		char[] cbuf = new char[1024];
		StringBuilder sb = new StringBuilder();
		while ((read.read(cbuf)) != -1) {
			sb.append(cbuf);
		}
		System.out.println(sb.toString().trim());
		logger.info("返回的报文：{}", sb.toString().trim());
		return httpConn.getResponseCode();
	}

	public static String getRemoteImage(String url) throws IOException {
		URL url1 = new URL(url);
		URLConnection conn = url1.openConnection();
		HttpURLConnection httpConn = (HttpURLConnection) conn;
		httpConn.setRequestMethod("GET");
		httpConn.setRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36");
		httpConn.setRequestProperty("Referer", "http://www.baidu.com/");
		httpConn.setRequestProperty("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
		httpConn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
		httpConn.setDoOutput(true);
		httpConn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
		InputStream is = httpConn.getInputStream();
		int index = url.lastIndexOf("/");
		String name = url.substring(index + 1);
		name = "D:/" + name;
		BufferedInputStream bis = new BufferedInputStream(is);
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name));
		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
		}
		bos.close();
		bis.close();
		logger.info("图片地址：{}" , name );
		return name;
	}

	public static Document getDocument(String url) throws Exception {
		URL url1 = new URL(url);
		URLConnection conn = url1.openConnection();
		HttpURLConnection httpConn = (HttpURLConnection) conn;
		httpConn.setRequestMethod("GET");
		httpConn.setRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36");
		httpConn.setRequestProperty("Referer", "http://www.baidu.com/");
		httpConn.setRequestProperty("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
		httpConn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
		httpConn.setDoOutput(true);
		httpConn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
		String encoding = httpConn.getContentEncoding();
		InputStreamReader read = null;
		InputStream is = httpConn.getInputStream();
		if ("gzip".equalsIgnoreCase(encoding)) {
			GZIPInputStream gzip = new GZIPInputStream(is);
			read = new InputStreamReader(gzip, "UTF-8");
		} else {
			read = new InputStreamReader(is, "UTF-8");
		}
		char[] cbuf = new char[1024];
		StringBuilder sb = new StringBuilder();
		while ((read.read(cbuf)) != -1) {
			sb.append(cbuf);
		}
		Document doc = Jsoup.parse(sb.toString());
		return doc;
	}
}
